// pages/detail-search/index.js
import {
  getSearchHot,
  getSearchSuggest,
  getSearchResult
} from "../../services/search"

import debounce from "../../utils/debounce"
import stringToNodes from "../../utils/stringToNodes"


//对数据请求进行防抖处理
const debounceGetSearchSuggest = debounce(getSearchSuggest, 100)

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hotKeyWords: [],
    suggestSongs: [],
    suggestSongsNodes: [],
    resultSongs: [],
    searchValue: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取页面数据
    this.getPageData()
  },

  // 网络请求
  getPageData: function () {
    getSearchHot().then(res => {
      this.setData({
        hotKeyWords: res.result.hots
      })
    })
  },

  // 事件处理
  handleSearchChange: function (event) {
    //获取输入关键字
    const searchValue = event.detail

    //保存关键字
    this.setData({
      searchValue
    })

    //判断关键字为空字符串
    if (!searchValue.length) {
      this.setData({
        suggestSongs: [],
        resultSongs: []
      })

      debounceGetSearchSuggest.cancel()
      return
    }

    //根据关键字进行搜索
    //进行防抖处理
    debounceGetSearchSuggest(searchValue).then(res => {
      //获取建议的关键字歌曲
      const suggestSongs = res.result.allMatch
      this.setData({
        suggestSongs
      })
      if (suggestSongs) return

      //转成node节点展示
      const suggestKeyWords = suggestSongs.map(item => item.keyword)
      const suggestSongsNodes = []
      for (const keywords of suggestKeyWords) {
        const nodes = stringToNodes(keywords, searchValue)
        suggestSongsNodes.push(nodes)
      }
      this.setData({
        suggestSongsNodes
      })
    })
  },

  handleSearchAction: function () {
    const searchValue = this.data.searchValue
    getSearchResult(searchValue).then(res => {
      this.setData({
        resultSongs: res.result.songs
      })
    })
  },
  handleKeywordItemClick: function (event) {
    const keyword = event.currentTarget.dataset.keyword
    this.setData({
      searchValue: keyword
    })
    this.handleSearchAction()
  }
})